package com.example.h9iserver.controller;

import com.example.h9iserver.domain.query.ChatCompletionQuery;
import com.example.h9iserver.service.ChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 聊天controller
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("chat")
@Slf4j
public class ChatController {

    private final ChatService chatService;
    // 线程池处理异步流式任务
    private final ExecutorService executorService = Executors.newCachedThreadPool();

    /**
     * 完成对话，返回前端内容
     */
    @PostMapping("completion")
    public String chatCompletion(@RequestBody ChatCompletionQuery chatCompletionQuery){
        return chatService.completion(chatCompletionQuery);
    }

    /**
     * 流式对话接口，支持多轮上下文
     * 前端通过EventSource连接此接口接收流式数据
     */
    @PostMapping(value = "completion/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamChat(@RequestBody ChatCompletionQuery chatCompletionQuery) {

        return chatService.completionStream(chatCompletionQuery);
    }
}
